﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Texfina.Core.Web;
using Texfina.Core.Common;
using Texfina.Entity.Sy;
using SYBOQry = Texfina.BOQry.Sy;

namespace Texfina.ERP
{
   public partial class wfMenu : PageBase
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         this.LoadInPostBack();

         if (this.IsPostBack)
            return;

         this.BuildTreeMenu();
      }

      private void BuildTreeMenu()
      {
         EUsuMenu objE = new EUsuMenu();

         objE.IdUser = Session[ConstSessionVar.USERID].ToString();

         SYBOQry.IUsuario objBO = WCFHelper.GetObject<SYBOQry.IUsuario>(typeof(SYBOQry.Usuario));

         DataTable dt = objBO.GetMenuAsignado(objE);

         foreach (DataRow dr in dt.Rows)
         {
            TreeNode nod = new TreeNode();

            nod.Text = dr["dsMenu"].ToString();
            nod.Value = dr["idMenu"].ToString();
            nod.Target = "dataArea";
            if (dr["dsWebPage"].ToString() != "")
               nod.NavigateUrl = dr["dsWebPage"].ToString();
            else
               nod.NavigateUrl = "javascript:void(0)";
            if (!string.IsNullOrEmpty(dr["dsImgPath"].ToString().Trim()))
               nod.ImageUrl = this.ResolveUrl(dr["dsImgPath"].ToString());
            else
               nod.ImageUrl = this.ResolveUrl(this.GetRootIconsPath("EditOption.png"));

            if (string.IsNullOrEmpty(dr["idPadre"].ToString().Trim()))
            {
               tvwMenu.Nodes.Add(nod);
               nod.ImageUrl = this.ResolveUrl(this.GetRootIconsPath("FolderClose.png"));
            }
            else
            {
               TreeNode nodP = GetNodeParent(dr["idPadre"].ToString(), tvwMenu.Nodes);

               if (nodP != null)
               {
                  nodP.ChildNodes.Add(nod);
                  nodP.ImageUrl = this.ResolveUrl(this.GetRootIconsPath("FolderClose.png"));
               }
            }

         }

         if (tvwMenu.Nodes.Count != 0)
         {
            tvwMenu.CollapseAll();
            tvwMenu.Nodes[0].Expand();
         }

      }

      private TreeNode GetNodeParent(string key, TreeNodeCollection nodes)
      {

         foreach (TreeNode node in nodes)
         {
            if (node.Value == key)
               return node;
            else
            {
               TreeNode nodeP = GetNodeParent(key, node.ChildNodes);
               if (nodeP != null)
               {
                  if (nodeP.Value == key)
                     return nodeP;
               }
            }
         }

         return null;

      }
   }

}